package com.cskaoyan.mall.search.mq;

import com.cskaoyan.mall.mq.constant.MqTopicConst;
import com.cskaoyan.mall.search.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class OnSaleMessageConsumer {
    @Value("${rocketmq.producer.group}")
    String producerGroup;

    @Value("${rocketmq.namesrv.addr}")
    String namesrvAddr;

    @Autowired
    SearchService searchService;

    @PostConstruct
    public void onSaleMessageConsumer() throws MQClientException {
        //这里要接收对应的消息
        DefaultMQPushConsumer defaultMQPushConsumer = new DefaultMQPushConsumer(producerGroup);
        defaultMQPushConsumer.setNamesrvAddr(namesrvAddr);
        defaultMQPushConsumer.subscribe(MqTopicConst.PRODUCT_ONSALE_TOPIC,"*");
        defaultMQPushConsumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                try {
                    log.info("接收到信息");
                    MessageExt messageExt = list.get(0);
                    byte[] body = messageExt.getBody();
                    String skuIdStr = new String(body, StandardCharsets.UTF_8);
                    Long skuId= Long.valueOf(skuIdStr);
                    //然后要调用对应的方法执行
                    searchService.upperGoods(skuId);
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }catch (Exception e){
                    log.error(e.getMessage());
                    return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                }
            }
        });
        defaultMQPushConsumer.start();
    }
}
